#include "ct.server.h"

#include <cstring>

TOB::CT::Server* TOB::CT::Server::instance = NULL;

TOB::CT::Server::Server() {
  instance = this;
}

TOB::CT::Server* TOB::CT::Server::getInstance() {
  if (instance == NULL) {
    instance = new TOB::CT::Server();
  }
  return this;
}

Code::Type TOB::CT::Server::connectNewUser(Userdata& user) {
  if (stackMsg.find(user.username) == stackMsg.end()) {
    stackEvent.erase(stackEvent.find(user.username));
    stackMsg[user.username] = std::vector<GetMessage>;
    stackEvent[user.username] = std::vector<CharEvent::Type>;
    
    GetMessage tmpSMsg;
    memcpy(tmpSMsg.data, "connect\0");
    memcpy(tmpSMsg.user, user.username);
    tmpSMsg.type = static_cast<int>(MessageType::status);
    tmpSMsg.time = static_cast<time_t>(time(NULL));
    
    for (auto it = stackMsg.begin(), it != stackMsg.end(), it++) {
        stackMsg[(*it).first].push_back(tmpSMsg);
      stackEvent[(*it).first].push_back(ChatEvent::UpdateUsers);
      stackEvent[(*it).first].push_back(ChatEvent::StatusMsg);
    }
    
    for (int i = 0; i < stackLog.size(); ++i) {
        stackMsg[user.username].push_back(stackLog[i]);
      stackEvent[user.username].push_back(ChatEvent::Msg);
    }
  }
  return Code::Okay;
}

Code::Type TOB::CT::Server::dissconnectUser(Userdata& user) {
  if (stackMsg.find(user.username) != stackMsg.end()) {
    stackEvent.erase(stackEvent.find(user.username));
    stackMsg.erase(stackMsg.find(user.username));
  }
  return Code::Okay;
}

Code::Type TOB::CT::Server::sendMesage(SendMessage& msg) {
  GetMessage tmpSMsg;
  memcpy(tmpSMsg.data, msg.data);
  memcpy(tmpSMsg.user, msg.user.username);
  tmpSMsg.type = static_cast<int>(MessageType::incoming);
  tmpSMsg.time = static_cast<time_t>(time(NULL));
}
